package com.wm.wmim.connect.center.manager;

import com.wm.wmim.common.enums.RedisKeyEnum;
import com.wm.wmim.connect.center.api.bo.RouteInfoBO;
import com.wm.wmim.connect.center.api.bo.req.RouteDeleteReqBO;
import com.wm.wmim.connect.center.api.bo.req.RouteSaveReqBO;
import com.wm.wmim.connect.center.api.bo.resp.RouteGetRespBO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author weiming
 * @date 2024/12/2 9:48
 * @description
 */
@Service
public class RouteManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void saveRoute(RouteSaveReqBO reqBO)  {
        /**
         * TODO 如果宕机了, 那这个用户连接和机器IP的路由就不准确了, 此时怎么将这个路由删掉, 需要兜底操作
         * 可以给redis加一个过期时间，然后定时任务去维护各个连接的路由，但是这样需要保存sessionId 和路由的关系
         * 或者，就先不管他，等有人往那里推消息的时候，会发现其实不在线，此时干掉该路由。
         */
        HashOperations<String, Object, RouteInfoBO> opsForHash = redisTemplate.opsForHash();
        String key = String.format(RedisKeyEnum.USER_ROUTE_KEY_NEW.getCode(), reqBO.getBusinessScene(), reqBO.getUserId());
        if (opsForHash.size(key) >= 10){
            throw new RuntimeException("连接太多数量过多! 请退出一个!");
        }
        RouteInfoBO routeInfoBO = new RouteInfoBO();
        routeInfoBO.setUserId(reqBO.getUserId());
        routeInfoBO.setUserCode(reqBO.getUserCode());
        routeInfoBO.setIp(reqBO.getIp());
        routeInfoBO.setDubboPort(reqBO.getDubboPort());
        routeInfoBO.setWsSessionId(reqBO.getWsSessionId());
        routeInfoBO.setBusinessScene(reqBO.getBusinessScene());

        opsForHash.put(key, reqBO.getWsSessionId(), routeInfoBO);
    }

    public void deleteRoute(RouteDeleteReqBO reqBO)  {
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        String key = String.format(RedisKeyEnum.USER_ROUTE_KEY_NEW.getCode(), reqBO.getBusinessScene(), reqBO.getUserId());
        opsForHash.delete(key, reqBO.getWsSessionId());
        if (opsForHash.size(key) <= 0){
            redisTemplate.delete(key);
        }
    }


    public RouteGetRespBO getRouteInfo(String businessScene, Long userId){
        RouteGetRespBO routeGetRespBO = new RouteGetRespBO();
        routeGetRespBO.setUserId(userId);
        String key = String.format(RedisKeyEnum.USER_ROUTE_KEY_NEW.getCode(), businessScene, userId);
        HashOperations<String, Object, RouteInfoBO> opsForHash = redisTemplate.opsForHash();
        List<RouteInfoBO> values1 = opsForHash.values(key);
        if (CollectionUtils.isEmpty(values1)){
            return routeGetRespBO;
        }
        routeGetRespBO.setRouteInfoBOList(values1);
        return routeGetRespBO;
    }


}
